import json
import logging
import os
import random
import string
import time

import requests

from bqtool.ai.kafka_kit import Kafka_consumer, Kafka_producer


def ranstr(num):
    salt = ''
    for i in range(num):
        salt += random.choice(string.ascii_uppercase + string.digits)
    return salt

def rannum(num):
    salt = ''
    for i in range(num):
        salt += random.choice(string.digits)
    return salt


def init_log():
    logger = logging.getLogger()
    logger.setLevel(level=logging.INFO)
    if len(logger.handlers) == 0:
        # handler = logging.FileHandler("log.txt")
        handler = logging.StreamHandler()
        handler.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    return logger


logger = init_log()
url = ''


def api(data):
    data = {"cdh":"1","jdchphm":"苏C1Z539","tp2_dzwjmc":"http://172.20.140.24:8009/pic?did=0&bid=144921328&pid=1082280964&ptime=1589909380","gcxh":"900718201420724823","gc_rqsj":1589528015023,"jdchpzldm":"1","tp3_dzwjmc":"http://172.20.140.24:8009/pic?did=0&bid=144921328&pid=1082271752&ptime=1589909380","kkbh":"2f6ad5c5a7af4e82a95543e5e5c80e1f","fxlx":"0"}
    if 'tp3_dzwjmc' in data and data['tp3_dzwjmc'] != '':
        hphm = data['jdchphm']
        logger.info(hphm)
        if hphm == '车牌' or hphm.strip() == '':
            hphm = ''
        param = {
            "version": 2,
            "imageUrls": [
                data['tp3_dzwjmc']
            ],
            "calcParam":
                "{\"Recognize\":{\"Call\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Crash\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Color\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Similar\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Marker\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Plate\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Sunroof\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Brand\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"SpareTire\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Rack\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Type\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Convertible\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Belt\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Danger\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Slag\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Lid\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"SchoolBus\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Taxi\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Manned\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Face\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1}},\"Detect\":{\"DetectRegion\":[0,0,0,0],\"IsDet\":true,\"Version\":1001,\"MaxCarWidth\":0,\"Mode\":0,\"MinCarWidth\":0,\"Threshold\":20,\"Licence\":\""+
                hphm+"\"}}"
        }
        res = requests.post(url, json=param)
        res.encoding = 'utf-8'
        res = parseData(res.json(),data)
        logger.info(res)
        logger.info(res['ImageResults'][0]['Vehicles'][0]['Recognize']['Plate']['Licence'])
        return res


def parseData(jsonData,sourceData):
    timeArray = time.localtime(sourceData['gc_rqsj'] / 1000)
    stime = time.strftime("%Y%m%d%H%M%S", timeArray)
    ImageResult = res['ImageResults'][0]

    resData = {
        "MotorVehicleListObject": {
            "MotorVehicleObject": [
                {
                    "AppearTime": stime,
                    "MotorVehicleID": rannum(48),
                    "SourceID": rannum(41),
                    "StorageUrl1": sourceData['tp3_dzwjmc'],
                    "SubImageList": {
                        "SubImageInfoObject": [
                            {
                                "Type": "01",
                                "StoragePath": sourceData['tp3_dzwjmc'],
                                "ImageID": ranstr(41),
                                "EventSort": 17,
                                "ShotTime": stime,
                                # "Height": 1680,
                                "Data": "",
                                # "Width": 2048 ,
                                "FileFormat": "Other"
                            }
                        ]
                    },
                    "LeftTopY": 891,
                    "LeftTopX": 525,
                    "Direction": "9",
                    "PlateClass": "01",
                    "InfoKind": 1,
                    # "TollgateID": "ddb95ae9937045f5a6f5de7fea48629f",
                    "HasPlate": "true",
                    "VehicleColor": "4",
                    "SafetyBelt": 0,
                    "RightBtmY": 87,
                    "PlateColor": "6",
                    "RightBtmX": 1239,
                    "PlateNo": "苏C39522"
                }
            ]
        }
    }
    if 'sbbh' in sourceData:
        resData['DeviceID'] = sourceData['sbbh']
        resData['SubImageList']['SubImageInfoObject'][0]['DeviceID'] = sourceData['sbbh']
    if 'kkbh' in sourceData:
        resData['TollgateID'] = sourceData['kkbh']
    # resData['AppearTime'] =




if __name__ == '__main__':
    s = ranstr(40)
    n = rannum(40)
    try:
        url = os.getenv("AI_URL", "http://32.60.129.20:8082/recog/")
        bootstrap_server = os.getenv("BOOTSTRAP_SERVER", "32.60.129.7:9092")
        kafkatopic = os.getenv("TOPIC", "ehl-vehicle")
        consumer = Kafka_consumer(bootstrap_servers=bootstrap_server, kafkatopic=kafkatopic,
                                  groupid='seemo')
        sinktopic = os.getenv("SINKTOPIC", "trtest")
        producer = Kafka_producer(bootstrap_servers=bootstrap_server, kafkatopic=sinktopic,
                                  is_json=True)
        data = consumer.read_df()
        for message in data:
            try:
                logger.info('receive data')
                mes = json.loads(message.decode())
                res = api(mes)
                if res is not None:
                    producer.send_df(res)
                    break
            except:
                logger.exception("deal data error")
                break
    except:
        logger.exception("system error")
